/*
 * (C) Copyright 2006-2010 Nuxeo SAS (http://nuxeo.com/) and contributors.
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Lesser General Public License
 * (LGPL) version 2.1 which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/lgpl.html
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * Contributors:
 *     bstefanescu
 */
package org.nuxeo.gwt.habyt.app.client;

import com.google.gwt.dom.client.Document;
import com.google.gwt.dom.client.Element;
import com.google.gwt.dom.client.Style;
import com.google.gwt.dom.client.Style.Position;
import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.ui.Widget;

/**
 * @author <a href="mailto:bs@nuxeo.com">Bogdan Stefanescu</a>
 * 
 */
public class BusyIndicator {

    protected Widget target;

    protected Element busy;

    public BusyIndicator() {
        this(null);
    }

    public BusyIndicator(Widget target) {
        this.target = target;
    }

    protected Element createBusy() {
        Element busy = DOM.createDiv();
        // DOM.setStyleAttribute(busy, "backgroundRepeat", "no-repeat");
        // DOM.setStyleAttribute(busy, "backgroundAttachment", "fixed");
        // DOM.setStyleAttribute(busy, "backgroundPosition", "center");
        // DOM.setStyleAttribute(busy, "backgroundImage",
        // "url(big_loading.gif)");
        Style style = busy.getStyle();
        style.setPosition(Position.ABSOLUTE);
        style.setBackgroundColor("yellow");
        style.setOpacity(0.2);
        style.setZIndex(100000);
        if (target == null) {
            Element body = Document.get().getBody();
            style.setLeft(0, Unit.PX);
            style.setTop(0, Unit.PX);
            style.setWidth(body.getOffsetWidth(), Unit.PX);
            style.setHeight(body.getOffsetHeight(), Unit.PX);
        } else {
            style.setLeft(target.getAbsoluteLeft(), Unit.PX);
            style.setTop(target.getAbsoluteTop(), Unit.PX);
            style.setWidth(target.getOffsetWidth(), Unit.PX);
            style.setHeight(target.getOffsetHeight(), Unit.PX);
        }
        return busy;
    }

    public void show() {
        busy = createBusy();
        Document.get().getBody().appendChild(busy);
    }

    public void remove() {
        if (busy != null) {
            busy.removeFromParent();
            busy = null;
        }
    }
}
